<template>
  <div>
    <el-menu class="el-menu-demo" mode="horizontal" background-color="#334157" text-color="#fff" active-text-color="#fff">
      <el-button class="buttonimg">
        <img class="showimg" :src="collapsed?imgsq:imgshow" @click="toggle(collapsed)">
      </el-button>

      <el-badge :value="messageCount" :max="99" :hidden="hiddenBadge" class="item" style="float: right;margin-top: 12px;margin-right: 25px;">
        <el-button size="small" @click="handleMessage">消息</el-button>
      </el-badge>

      <el-submenu index="1" class="submenu" >
        <template slot="title">
          <el-avatar :src="$store.state.userAvatar" />
          <span>{{ $store.state.userName }}</span>
        </template>
        <el-menu-item @click="userCenter" index="1-1" style="width: 30px;"><font>个人中心</font></el-menu-item>
        <el-menu-item @click="userCenter" index="1-2" style="width: 30px;"><font>修改密码</font></el-menu-item>
        <el-menu-item @click="exit()" index="1-3" style="width: 30px;"><font>退出</font></el-menu-item>
      </el-submenu>
    </el-menu>

    <el-dialog
      title="消息中心"
      :visible.sync="centerDialogVisible"
      fullscreen
      center>
      <el-divider></el-divider>
          <el-button @click="allRead" size="small" type="success" icon="el-icon-check" style="margin-bottom: 20px;">全部已读</el-button>
          <el-button @click="del" size="small" icon="el-icon-document-delete" type="danger" style="margin-bottom: 20px;">删除</el-button>
          <el-button @click="delAll" size="small" icon="el-icon-document-delete" type="danger" style="margin-bottom: 20px;">全部删除</el-button>
          <!--    系统消息列表    -->
          <el-table :data="messageList" border style="width: 100%"  tooltip-effect="dark" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="40"></el-table-column>
            <el-table-column align="center" label="序号" width="100" type="index"></el-table-column>
            <el-table-column align="center" prop="fromUserName" label="发送人" width="300" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column align="center" prop="fromUserRole" label="发送人角色" width="300" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column align="center" prop="messageContent" label="消息内容" width="700" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column align="center" prop="createTime" label="发送时间" width="200">
              <template slot-scope="scope">
                {{ getFormat(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column align="center" prop="messageStatus" label="状态" >
              <template slot-scope="scope">
                <el-tag v-if="scope.row.messageStatus === 2" type="danger">未读</el-tag>
                <el-tag v-if="scope.row.messageStatus === 1" type="success">已读</el-tag>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <div style="margin-top: 10px;">
            <el-pagination background
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           :current-page="query.pageNo"
                           :page-sizes="[15, 50]"
                           :page-size="query.pageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="query.total">
            </el-pagination>
          </div>



    </el-dialog>

  </div>




</template>
<script>
import { newMessageCount, getMessageList, allReadMessage, deleteMessage, deleteAllMessage } from "@/api/user";
import { logout } from "@/api/auth";
import { getLoginUserId, delUserId, delUserToken, delUserRole } from "@/utils/userToken";
import { dateFormat } from '@/utils/date';
export default {
  name: 'navcon',
  data() {
    return {
      centerDialogVisible: false,
      collapsed: true,
      imgshow: require('../../assets/images/show.png'),
      imgsq: require('../../assets/images/sq.png'),
      clickItem: "1",
      messageCount: 0,
      hiddenBadge: true,
      messageList: [],
      query: {
        pageNo: 1,
        pageSize: 15,
        total: 0
      },
      checkedIds: []
    }
  },

  created() {
    this.clickItem = 1;
    this.getUserNewMessage();
  },

  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },

    message() {
      this.drawer = true;
    },

    delAll() {
      this.$confirm('确认删除全部消息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAllMessage().then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
            // 刷新列表
            this.getUserNewMessage();
            this.fetchMessageList();
          } else {
            this.$notify.error({
              title: '错误',
              message: response.message,
              duration: 1500
            });
          }
        })
      }).catch(() => {
        // 取消删除
      });
    },

    allRead() {
      this.$confirm('确认设置全部已读吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        allReadMessage().then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '设置成功',
              type: 'success',
              duration: 1500
            });
            // 刷新列表
            this.getUserNewMessage();
            this.fetchMessageList();
          } else {
            this.$notify.error({
              title: '错误',
              message: response.message,
              duration: 1500
            });
          }
        })
      }).catch(() => {
        // 取消删除
      });
    },

    // 获取全部消息
    fetchMessageList() {
      getMessageList(this.query).then(res => {
        if (res.code === 200) {
          this.messageList = res.data.list;
          this.query.total = res.data.total;
        }
      })
    },

    del() {
      if (this.checkedIds.length === 0) {
        this.$notify.error({
          title: '错误',
          message: '请至少选择一条消息',
          duration: 1500
        });
        return;
      }

      this.$confirm('确认删除这些消息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {
          ids: []
        }
        data.ids = this.checkedIds;
        deleteMessage(data).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
            // 刷新列表
            this.getUserNewMessage();
            this.fetchMessageList();
            this.checkedUserIds = [];
          } else {
            this.$notify.error({
              title: '错误',
              message: response.message,
              duration: 1500
            });
          }
        })
      }).catch(() => {
        // 取消删除
        this.checkedUserIds = [];
      });
    },

    // 获取当前用户的未读消息数
    getUserNewMessage() {
      newMessageCount().then(res => {
        if (res.code === 200) {
          const resData = res.data;
          if (resData > 0) {
            this.hiddenBadge = false;
            this.messageCount = resData;
          } else {
            this.hiddenBadge = true;
          }
        }
      })
    },

    userCenter() {
      this.$router.push("/system/userCenter")
    },

    // 打开消息的弹框
    handleMessage() {
      this.centerDialogVisible = true;
      this.fetchMessageList();
    },

    handleSelectionChange(val) {
      this.checkedIds = [];
      let len = JSON.parse(JSON.stringify(val))
      if (len.length !== 0) {
        for (let i = 0; i < len.length; i++) {
          this.checkedIds.push(len[i].id)
        }
      } else {
        this.checkedIds = len
      }
    },

    clickMenuItem(id) {
      this.clickItem = id;
    },

    // 格式化日期
    getFormat(date){
      if (date) {
        return dateFormat(date);
      }
      return ""
    },

    // val 是切换之后的每页显示多少条
    handleSizeChange(val) {
      this.query.pageSize = val;
      this.fetchMessageList();
    },

    // 当页码改变后触发此方法 val是当前点击（或输入）的页码
    handleCurrentChange(val) {
      this.query.pageNo = val;
      this.fetchMessageList();
    },

    // 退出登录
    exit: function () {
      this.$confirm('确认退出吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        logout(getLoginUserId()).then(res => {
          if (res.code === 200) {
            this.$notify({
              title: '成功',
              message: '退出成功',
              type: 'success',
              duration: 1500
            });
          }
          delUserId();
          delUserToken();
          delUserRole();
          this.$router.push('/login')
        })
      }).catch(() => {
        // 取消删除
      });
    },
    // 切换显示
    toggle(showtype) {
      this.collapsed = !showtype
      this.$root.Bus.$emit('toggle', this.collapsed)
    }
  }
}
</script>
<style scoped>

.el-menu-vertical-demo:not(.el-menu--collapse) {
  border: none;
}
.submenu {
  float: right;
}
.buttonimg {
  height: 60px;
  background-color: transparent;
  border: none;
}
.showimg {
  width: 26px;
  height: 26px;
  position: absolute;
  top: 17px;
  left: 17px;
}
.showimg:active {
  border: none;
}

.drawer-title {
  text-align: center;
  width: 100%;
}

</style>
